package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    //封装获得的 对象
    public void upload(List<String[]> list) {
        //遍历 数据 封装到对象
        for (String[] strings : list) {
            String orderDate = strings[0];
            String number = strings[1];
            //数据封装到对象里面
            OrderSetting orderSetting = new OrderSetting(new Date(orderDate), Integer.parseInt(number));
            //根据 日期查询一下 数据库是否 已经写入过
            long l =  orderSettingDao.countOrderDate(orderDate);
            if (l > 0) {
                //这个日期已经存过了 要做 更新操作
                orderSettingDao.update(orderSetting);
            } else {
                //这个日期没存过 直接写入
                orderSettingDao.add(orderSetting);
            }
        }
    }

    @Override
    public List<Map> getOrderSettingByMonth(String dateString) { //date参数 2020-9 这种

        String start = dateString + "-1";
        String end = dateString + "-31";

        List<OrderSetting> list = orderSettingDao.getOrderSettingByMonth(start,end);

        List<Map> listMap = new ArrayList<>();

        if (list != null) {
            for (OrderSetting orderSetting : list) {
                int date = orderSetting.getOrderDate().getDate();
                int number = orderSetting.getNumber();
                int reservations = orderSetting.getReservations();
                Map<String, Integer> map = new HashMap<>();
                map.put("date",date);
                map.put("number",number);
                map.put("reservations",reservations);
                //封装好的参数 放近list集合
                listMap.add(map);
            }
        }

        return listMap;
    }

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        String format = new SimpleDateFormat("yyyy-MM-dd").format(orderSetting.getOrderDate());

        long l = orderSettingDao.countOrderDate(format);
        if (l > 0) {
            orderSettingDao.update(orderSetting);
        } else {
            orderSettingDao.add(orderSetting);
        }
    }
}
